package com.kdgc.power.common.util;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class FileUtil {

    private static int i;

    public static void deleteFile(String filePath) throws IOException {
        FileUtils.forceDelete(filePath);
    }

    public static void write(File path, String context) throws Exception {
        if (!path.exists()) path.getParentFile().mkdirs();
        FileUtils.fileWrite(path.getAbsolutePath(), context);
    }

    public static String read(File path) throws IOException {
        return FileUtils.fileRead(path.getAbsolutePath());
    }


    public static void findAndUse(File dir, Predicate<File> filter, Consumer<File> consumer) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file != null) {
                    if (file.isDirectory()) {
                        findAndUse(file, filter, consumer);
                    } else if (filter.test(file)) {
                        consumer.accept(file);
                    }
                }
            }
        }

    }

    public  static void findByFuzzy(String dirPath, String fileName) {
        File dir = new File(dirPath);
        if (dir.isDirectory()) {
              findAndUse(dir, file -> file.getName().contains(fileName), file -> System.out.println(file.getAbsolutePath()));
        }
    }

    public static void copyByFuzzy(String oldDir, String newDir, String fuzzy) throws Exception {
        copyByCondition(oldDir, newDir, file -> file.getName().contains(fuzzy));
    }

    public static void copyByCondition(String oldDir, String newDir, Predicate<File> filter) throws Exception {
        File[] files = new File(oldDir).listFiles();
        if (files != null) {
            for (File file : files) {
                if (file != null) {
                    if (file.isDirectory()) {
                        copyByCondition(file.getAbsolutePath(), newDir, filter);
                    } else if (filter.test(file)) {
                        int index = file.getName().lastIndexOf(".");
                        String name = file.getName().substring(0, index);
                        String type = file.getName().substring(index);
                        File temp = new File(newDir, file.getName());
                        if (temp.exists()) {
                            temp = new File(newDir, name + "_" + (++i) + type);
                        }
                        FileUtils.copyFile(file,temp);
                    }
                }
            }
        }
    }
}
